﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

using RushTracker.Core.Windsor;
using RushTracker.Web.Routing;
using RushTracker.Web.UI.Handlers;
using RushTracker.Core.Util;
using RushTracker.Web.UI;

namespace RushTracker.Web
{
    public class RushTrackerApplication : HttpApplication, IContainerAccessor
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            RushTracker.Core.Site.Instance.Initialize(HttpContext.Current.Server.MapPath("~/rushTracker.config"));

            IoC.Initialize(new WindsorContainer(new XmlInterpreter()));
            ControllerBuilder.Current.SetControllerFactory(typeof(WindsorControllerFactory));

            InitializeWindsor();
            RegisterRoutes(RouteTable.Routes);
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpHandler<AnnounceHandler>("announce/{key}/");
    //        routes.MapHttpHandler<DownloadHandler>("torrent/download/{id}");

            routes.MapRouteLowerCase("UsersLogin", "login", new { controller = "Users", action = "Login" });
            routes.MapRouteLowerCase("UsersLogout", "logout", new { controller = "Users", action = "Logout" });
            routes.MapRouteLowerCase("UsersCreate", "signup", new { controller = "Users", action = "Create" });
            routes.MapRouteLowerCase("UsersView", "profile/{userId}", new { controller = "Users", action = "View", userId = "" });
            routes.MapRouteLowerCase("UsersEdit", "profile/settings/{userId}", new { controller = "Users", action = "Edit", userId = "" });
            routes.MapRouteLowerCase("TorrentsCategory", "torrents/category/{categoryId}", new { controller = "Torrents", action = "ListByCategory", categoryId = "" });
            routes.MapRouteLowerCase("TorrentsTags", "torrents/tags/{tags}", new { controller = "Torrents", action = "ListByTags", tags = "" });
            routes.MapRouteLowerCase("TorrentShow", "torrent/{torrentId}", new { controller = "Torrents", action = "Show", torrentId = "" });
            routes.MapRouteLowerCase("TorrentEdit", "torrent/edit/{torrentId}", new { controller = "Torrents", action = "Edit", torrentId = "" });
            routes.MapRouteLowerCase("TorrentsUpload", "upload", new { controller = "Torrents", action = "Upload" });
            routes.MapRouteLowerCase("TorrentsUploadSuccess", "upload/success", new { controller = "Torrents", action = "UploadSucceeded" });
            //routes.MapRouteLowerCase("TorrentsDownload", "torrent/download/{torrentId}", new { controller = "Torrents", action = "Download", torrentId = "" });

            routes.MapRouteLowerCase("AdminCategories", "admin/categories", new { controller = "Admin", action = "ShowCategories" });
            routes.MapRouteLowerCase("AdminEditCategory", "admin/categories/edit/{catId}", new { controller = "Admin", action = "EditCategory", catId = "" });
            routes.MapRouteLowerCase("AdminCreateCategory", "admin/categories/create", new { controller = "Admin", action = "CreateCategory" });

            routes.MapRouteLowerCase("AdminMetaFields", "admin/metafields", new { controller = "Admin", action = "ShowMetaFields" });
            routes.MapRouteLowerCase("AdminCreateMetaField", "admin/metafields/create", new { controller = "Admin", action = "CreateMetaField" });
            routes.MapRouteLowerCase("AdminEditMetaField", "admin/metafields/edit/{metaFieldId}", new { controller = "Admin", action = "EditMetaField", metaFieldId = "" });
            
            routes.MapRouteLowerCase("AdminRoles", "admin/roles", new { controller = "Admin", action = "ShowRoles" });
            routes.MapRouteLowerCase("AdminEditRole", "admin/roles/edit/{roleId}", new { controller = "Admin", action = "EditRole", roleId = "" });
            routes.MapRouteLowerCase("AdminCreateRole", "admin/roles/create", new { controller = "Admin", action = "CreateRole" });

            routes.MapRouteLowerCase(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );
        }

        private void InitializeWindsor()
        {

            if (Container == null)
            {
                throw new InvalidOperationException("Unable to load controllers. Container is null.");
            }

            Type[] types = Assembly.GetExecutingAssembly().GetTypes();

            foreach (Type t in types)
            {
                if (typeof(RushTrackerController).IsAssignableFrom(t))
                {
                    Container.AddComponentLifeStyle(t.Name, t, Castle.Core.LifestyleType.Transient);
                }
            }

        }

        #region IContainerAccessor Members

        public IWindsorContainer Container
        {
            get { return IoC.Container; }
        }

        #endregion
    }
}
